import React, { Component } from 'react';
import Style from './index.module.scss';
import { Form, Icon, Input, Button, message } from 'antd';
import { FormComponentProps } from 'antd/lib/form';
import { userNameReg, passReg, codeReg } from '../../utils/validate'
import { Api } from '../../ajax/api'
import { connect } from 'react-redux'
import { loginAction } from '../../store/auth/actions'
import { RouteComponentProps } from 'react-router-dom'
import { StoreType } from '../../store/types'
import { Redirect } from "react-router-dom";

interface StateInterface {
  // 验证码图片URL
  codeImgUrl: string
}

interface StorePopInterface {
  isLogin: boolean,
  loginAction: (user: string, pass: string, code: string) => Promise<any>
}

interface PropsInterface extends FormComponentProps, StorePopInterface, RouteComponentProps {
}

class Login extends Component<PropsInterface, StateInterface> {

  constructor(props: PropsInterface) {
    super(props)

    this.handleSubmit = this.handleSubmit.bind(this)
    this.codeImgClick = this.codeImgClick.bind(this)
  }

  state: Readonly<StateInterface> = {
    codeImgUrl: Api.user.verificationCode
  }

  /**
   * 确定按钮点击
   */
  handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        message.error('请完成填写')
      } else {
        this.props.loginAction(values.user, values.pass, values.code).then((data) => {
          this.props.history.push(`/admin`)
        }).catch(() => {
          this.codeImgClick()
        })
      }
    });
  }

  /**
   * 验证码按钮点击
   */
  codeImgClick() {
    this.setState(() => {
      return {
        codeImgUrl: `${Api.user.verificationCode}?t=${new Date().getTime()}`
      }
    })
  }

  render(): React.ReactElement<any, string | React.JSXElementConstructor<any>> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
    const { getFieldDecorator } = this.props.form;
    const { isLogin } = this.props

    if (isLogin) {
      return <Redirect to={ '/admin' } />;
    }

    return (
      <div className={`w-image-fit ${Style.login}`}>
        <Form onSubmit={this.handleSubmit} className={Style['login-form']}>
        <h3 className={ 'w-text-center' }>登录</h3>
          <Form.Item>
            {getFieldDecorator('user', {
              rules: [
                { required: true, message: '请输入用户名' },
                { pattern: userNameReg, message: '4-20位字符数字' }
              ],
            })(
              <Input
                prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder="用户名"
                onPressEnter={ this.handleSubmit }
              />,
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('pass', {
              rules: [
                { required: true, message: '请输入密码' },
                { pattern: passReg, message: '6-20位字符数字' }
              ],
            })(
              <Input
                prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                type="password"
                placeholder="密码"
                onPressEnter={ this.handleSubmit }
              />,
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('code', {
              rules: [
                { required: true, message: '请输入密码' },
                { pattern: codeReg, message: '4位字符数字' }
              ],
            })(
              <Input
                className={ Style['code-input'] }
                prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder="验证码"
                onPressEnter={ this.handleSubmit }
              />,
            )}
            <img 
              onClick={ this.codeImgClick } 
              className={ `w-pointer ${Style['code-img']}` } 
              src={ this.state.codeImgUrl } alt=""
            />
          </Form.Item>
          <Form.Item className={ Style['clear-form-item-margin'] }>
            <Button htmlType="submit" type="primary" className={ Style['login-form-button'] }>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

const LoginFromCom = Form.create<PropsInterface>({})(Login);

const mapStateToProps = (state: StoreType) => {
  return {
    isLogin: state.auth.user ? true : false
  }
}

const mapDispatchToProps = (dispatch: any) =>{
  return {
    loginAction: (user: string, pass: string, code: string) => dispatch(loginAction(user, pass, code))
  }
}

const classModel = connect(
  mapStateToProps,
  mapDispatchToProps,
  null,
  {
    forwardRef: true 
  }
)(LoginFromCom)
export default classModel
